<?php
/**
 * Created by PhpStorm.
 * User: xding
 * Date: 15/10/28
 * Time: 上午9:37
 */

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Media manager
 *
 * Class Media
 */
class Media extends MY_Controller {

    private $media_num_one_page = 12;

    public function index( $start = 0 ) {

        $type = $this->input->get('type') ?: 'all';

        $this->load->model('medias_model','medias');

        $path = $this->medias->get_path($type);
        if ( !$path )
        {
            show_error("不存在的媒体类型");
        }

        $data['media_arr'] = $this->medias
                                  ->initialize($path)
                                  ->sort('media_create_time','DESC')
                                  ->set_query_type($type)
                                  ->limit($start,$this->media_num_one_page)
                                  ->get();

        // create pagination
        $this->load->library('pagination');
        $config['base_url']   = base_url(array('media','index'));
        $config['total_rows'] = $this->medias
                                     ->set_query_type($type)
                                     ->get_media_count();
        // $config['total_rows'] = 100;

        $config['per_page']   = $this->media_num_one_page;
        $this->pagination->initialize($config);
        $data['page'] = $this->pagination->create_links();

        //dump($data);
        $this->load->view('media/index',$data);
    }


    public function upload() {
        $this->load->view('media/upload');
    }

    /**
     * 响应plupload插件的上传事件
     *
     * 插件官网上传方法
     */
    public function upload2plupload() {

        // Make sure file is not cached (as it happens for example on iOS devices)
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        /*
        // Support CORS
        header("Access-Control-Allow-Origin: *");
        // other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        */

        // 5 minutes execution time
        @set_time_limit(5 * 60);

        // Uncomment this one to fake upload time
        // usleep(5000);

        // Settings
        //$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        //$targetDir = 'uploads';
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }

        // 根据扩展名获取文件上传路径
        $this->load->model('medias_model','medias');
        $targetDir = $this->medias->get_path($this->medias->get_media_type($fileName));
        if ( !$targetDir )
        {
            die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Unknown upload path"}, "id" : "id"}');
        }

        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}.part") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


        // Open temp file
        if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
            // Strip the temp .part suffix off
            rename("{$filePath}.part", $filePath);
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

    /**
     * 响应CKEditor上传图片
     */
    public function uploadimg2ck () {
        // 回调值
        $ckeditor_funcnum = $this->input->get('CKEditorFuncNum');
        // form field -----> upload
        $form_field = 'upload';

        $config['upload_path']      = IMAGE_UPLOAD_PATH;
        // image type
        $config['allowed_types']    = 'gif|jpg|png|jpeg';

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload($form_field))
        {
            //$error = array('error' => $this->upload->display_errors());
            $error = strip_tags($this->upload->display_errors());
            echo "<script>alert('上传失败{$error}');</script>";
            die();
        }
        else
        {
            // 此处传回的是图片的URL地址
            // $data = array('upload_data' => $this->upload->data());
            $upload_info = $this->upload->data();
            $img_url = base_url('public/resource/uploads/images') . '/' . $upload_info['file_name'];
            echo "<script>window.parent.CKEDITOR.tools.callFunction('" . $ckeditor_funcnum . "','" . $img_url . "', '')</script>";
            die();
        }
    }


    /**
     * 媒体输出，不同媒体调用不同输出方式
     */
    public function out() {

        $params = $this->input->get('params');
        if ( empty($params) )
        {
            exit(json_encode(array("404",array('msg'=>'file path not exists'))));

        }

        $_params = explode(',',$params);
        if ( !$_params || !is_array($_params) || !count($_params) )
        {
            exit(json_encode(array("404",array('msg'=>'file path not exists'))));
        }

        //dump($_params);

        // 获取文件路径
        $path = $_params[0];

        $this->load->helper('file');
        $this->load->model('medias_model','medias');

        // 路径解密
        $media = new \Beans\Media();
        //dump($path);
        $media->media_full_path = authcode2url($path,'DECODE',AUTHCODE_KEY);
        $media->media_name      = pathinfo($media->media_full_path,PATHINFO_BASENAME);
        $media->media_extension = pathinfo($media->media_full_path,PATHINFO_EXTENSION);
        $media->media_mime      = get_mime_by_extension($media->media_name);
        $media->media_type      = $this->medias->get_media_type($media->media_name);

        //dump($media);

        /**
         * 分类处理输出
         */
        switch ($media->media_type)
        {
            case 'image':
                $this->_image_out($media,$_params);
                break;
        }

    }


    /**
     * 输出图片
     *
     * @param \Beans\Media $media
     * @param $params
     */
    private function _image_out(\Beans\Media &$media, &$params) {

        $manager = new Intervention\Image\ImageManager();
        // 处理图片参数
        if ( 1 < count($params) )
        {
            $width = NULL;
            $height = NULL;
            $style = 'center';
            for ( $i = 1 ; $i < count($params) ; $i ++ )
            {
                $_temp = explode('_',$params[$i]);
                switch ($_temp[0])
                {
                    case 'w':
                        $width = intval($_temp[1]);
                        break;
                    case 'h':
                        $height = intval($_temp[1]);
                        break;
                }
            }

            // 重新命名图片名称
            $new_name = pathinfo($media->media_full_path,PATHINFO_FILENAME)
                         . ',w_' . $width . ',h_' . $height
                         . '.' . $media->media_extension;

            $new_path = IMAGE_CACHE_PATH . $new_name;

            // 在缓存中查找该文件是否存在
            if ( !file_exists($new_path) )
            {
                // 如果不存在，则缓存文件
                $image = $manager->make($media->media_full_path)
                                 ->resizeCanvas($width,$height,$style)
                                 ->save($new_path);
            }
            else
            {
                $image = $manager->make($new_path);
            }
        }
        else
        {
            // 没有其他参数,直接输出原图
            $image = $manager->make($media->media_full_path);
        }

        echo $image->response('jpg');
        unset($manager,$image,$media,$params);
        exit();
    }

}
